<?php
require 'System/Forms/OpdrachtForm.php';

class OpdrachtController extends Controller
{
	protected $requiresAuthentication = true;
	
	/**
	 * 
	 * @see Controller::defaultAction()
	 */
	public function defaultAction()
	{
		$view = new HTMLView( 'OpdrachtController/Overview', $this->getSmarty() );
		$view->assign( 'opdrachten', Opdracht::find('all') );
		
		$this->getViewManager()->push( $view );
	}
	
	public function createAction()
	{
		$this->showForm( );
	}
	
	public function editAction()
	{
		if( isset( $_GET['id'] ) )
		{
			$Opdracht = Opdracht::find( $_GET['id'] );

			if( $Opdracht == null )
			{
				throw new Exception('Opdracht with id ' . $_GET['id'] . ' was not found.');
			}
				
			$this->showForm( $Opdracht );
		}
		else
		{
			$this->defaultAction();
		}
	}
	
	public function showForm( Opdracht $opdracht = null )
	{

		$data = array();
		if( $opdracht != null )
		{
			$data = $opdracht->getAttributes();
			$view = new HTMLView( 'OpdrachtController/Edit', $this->getSmarty() );
			$view->assign( 'opdracht', $data );
		}
		else
		{
			$view = new HTMLView( 'OpdrachtController/Create', $this->getSmarty() );
		}
		
		$Opdracht = new OpdrachtForm( $_SERVER['REQUEST_METHOD'] == 'POST' ? $_POST : $data );
		
		$bedrijven = Bedrijf::find('all', array( 'order_by' => 'name' ));
		$Opdracht->setBedrijven( $bedrijven, $data['bedrijf_id'] );
		
		$view->assign('opdracht', $opdracht);
		
		$view->assignArray( array( 'form' => $Opdracht ) );

		$this->getViewManager()->remove( $view );
		$this->getViewManager()->push( $view );
		
		if( $_SERVER['REQUEST_METHOD'] == 'POST' && $Opdracht->isValid() )
		{
			$Opdracht = new Opdracht( $_POST );
			$Opdracht->save();

			$this->form_ViewConfirmation( $Opdracht );
		}
	}

	
	private function form_ViewConfirmation( Opdracht $Opdracht )
	{
		header('Location: ?c=Opdracht&a=detail&id=' . $Opdracht->getSugarId() . '&added=true');
	}
	
	public function detailAction()
	{
		if( isset( $_GET['id'] ) )
		{
			$Opdracht = Opdracht::find( $_GET['id'] );

			if( $Opdracht == null )
			{
				throw new Exception('Opdracht with id ' . $_GET['id'] . ' was not found.');
			}

			$view = new HTMLView( 'OpdrachtController/Detail', $this->getSmarty() );
			$view->assign( 'opdracht', $Opdracht );
			$view->assign( 'bedrijf', Bedrijf::find( $Opdracht->bedrijf_id ) );
			$view->assign( 'labels', Opdracht::getField('*') );
			$this->getViewManager()->push( $view );
		}
		else
		{
			$this->defaultAction();
		}
	}
	
	public function deleteAction()
	{
		if( isset( $_GET['id'] ) )
		{
			$Opdracht = Opdracht::find( $_GET['id'] );

			if( $Opdracht == null )
			{
				throw new Exception('Opdracht with id ' . $_GET['id'] . ' was not found.');
			}

			$Opdracht->delete();
		}
		
		$this->defaultAction();
	}
}